package com.example.controller;

import com.example.entity.Account;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author latin-xiao-mao
 * @date 2020/7/8 22:34
 * @description
 * @className AccountController
 */
@Controller
public class AccountController {


	@GetMapping("/{url}")
	public String redirect(@PathVariable("url") String url){

		return url;
	}



	@PostMapping("/login")
	public String login(String username, String password, Model model){

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
			// 登录之后，设置session，注意不能从token中去获取，因为token中保存的是用户输入的信息
			Account account = (Account) subject.getPrincipal(); // 由于已经验证过了，所以用户信息已经保存在 principal 中了，取出即可
			Session session = subject.getSession();
			// 将 account 存入 session中，供前台页面使用
			session.setAttribute("account", account);
			return "index";
		}catch (UnknownAccountException e){
			model.addAttribute("msg", "用户名不正确");
			e.printStackTrace();
			return "login";
		}catch (IncorrectCredentialsException e){
			e.printStackTrace();
			model.addAttribute("msg", "密码不正确");
			return "login";
		}

	}



	@GetMapping("/unauth")
	@ResponseBody
	public String unauth(){

		return "您未被授权访问此页面，无法访问";
	}



	@GetMapping("/logout")
	public String logout(){
		// shiro已经帮我们封装好了退出功能了，只需要调用内置的 logout方法即可
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
}
